package cn.tworice.netty.session;

import cn.tworice.netty.constand.MessageConst;
import io.netty.util.AttributeKey;
import lombok.Getter;
import lombok.Setter;

import io.netty.channel.Channel;
import org.springframework.util.StringUtils;

@Getter
@Setter
public class Session {

    /**
     * 唯一标识
     **/
    private String id;

    /**
     * 用户标识
     **/
    private String uid;

    /**
     * 组标识
     **/
    private String gid;

    /**
     * 客户端
     **/
    private Channel channel;

    /**
     * 上次通信时间
     **/
    private long lastCommunicateTimeStamp = 0L;

    /**
     * 构建一个Session
     * @param uid 用户标识
     * @param gid 组标识
     * @param channel 客户端
     **/
    public static Session buildSession(String uid, String gid, Channel channel) {
        Session session = new Session();
        session.setId(channel.id().asLongText());
        session.setChannel(channel);
        session.setUid(uid);
        session.setGid(gid);
        session.setLastCommunicateTimeStamp(System.currentTimeMillis());
        return session;
    }

    public static Session buildSession(Channel channel) {
        Session session = new Session();
        String uid = Session.<String>get(MessageConst.uid, channel);
        if (!StringUtils.isEmpty(uid)) session.setUid(uid);
        String gid = Session.<String>get(MessageConst.gid, channel);
        if (!StringUtils.isEmpty(gid)) session.setGid(gid);
        session.setId(channel.id().asLongText());
        session.setLastCommunicateTimeStamp(System.currentTimeMillis());
        session.setChannel(channel);
        return session;
    }

    /**
     * 从客户端中获取信息
     * @param key Key
     * @param channel io.netty.channel.Channel
     * @return T 结果
     **/
    public static <T> T get(String key,Channel channel) {
        AttributeKey<T> attributeKey = AttributeKey.valueOf(key);
        return channel.attr(attributeKey).get();
    }

    /**
     * 设置信息到客户端中
     * @param key Key
     * @param content 内容
     * @param channel io.netty.channel.Channel
     **/
    public static void set(String key,Object content, Channel channel) {
        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(content) || !channel.isOpen()) {
            return;
        }
        AttributeKey<Object> attributeKey = AttributeKey.valueOf(key);
        channel.attr(attributeKey).setIfAbsent(content);
    }
}
